<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" style="margin-top: 15px;" size="small" label-width="100px">
      <el-form-item label="咨询者" prop="subject">
        <div style="width: 646px" v-html="articleForm.user ? articleForm.user.username : ''" />
      </el-form-item>
      <el-form-item label="咨询详情" prop="tos">
        <div style="width: 646px" v-html="articleForm.queryContent" />
        <div v-if="articleForm.queryImages" class="demo-image__preview">
          <el-image
            v-for="url in JSON.parse(articleForm.queryImages)"
            :key="url"
            style="width: 200px; height: 100px; margin-right: 10px;margin-bottom: 10px;"
            :src="url"
            :preview-src-list="JSON.parse(articleForm.queryImages)"
          />
        </div>
      </el-form-item>
      <el-form-item label="提问时间" prop="createTime">
        <div style="width: 646px" v-html="articleForm.createTime ? articleForm.createTime : ''" />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input v-model="articleForm.price" :disabled="articleForm.queryAnswers && articleForm.queryAnswers.filter(v=>v.type === 0 || v.type === 1).length > 0" style="width: 100px" />
        <span>元</span>
      </el-form-item>
      <el-form-item label="免费回复" prop="tos">
        <div ref="summary" class="summary" />
      </el-form-item>
      <div>
        <el-button
          :loading="loading"
          style="margin-left:1.6%;margin-bottom: 10px"
          size="medium"
          type="primary"
          @click="doReply"
        >回复用户
        </el-button>
        <el-checkbox v-model="articleForm.sendSMS" style="margin:0 0 25px 0;">
          发送短信
        </el-checkbox>
      </div>
      <div v-if="articleForm.queryAnswers && articleForm.queryAnswers.filter(v=>v.type === 2 || v.type === 3).length > 0">
        <div style="margin-left:20px; color:#666;">历史回复</div>
        <div v-for="answer in articleForm.queryAnswers.filter(v=>v.type === 2 || v.type === 3)" :key="answer.id">
          <div v-if="answer.type === 2">
            <div style="margin-left: 20px;margin-top: 15px; color:#1890ff;">免费回复: {{ answer.answerTime }}</div>
            <div style="margin-left: 20px;width: 730px; margin-top: 10px; border: 1px solid #c9d8db; padding:15px; border-radius: 4px;background: #f2f2f2;" v-html="answer.answerContent" />
          </div>
          <div v-else-if="answer.type === 3">
            <div style="margin-left: 20px;margin-top: 15px; color: red;">咨询补充: {{ answer.answerTime }}</div>
            <div style="margin-left: 20px;width: 730px; margin-top: 10px; border: 1px solid #c9d8db; padding-left: 15px;padding-right: 15px; border-radius: 4px;">
              <p>{{ answer.queryContent }}</p>
            </div>
            <div v-if="answer.queryImages" class="demo-image__preview" style="margin-left: 20px;margin-top: 10px;">
              <el-image
                v-for="url in JSON.parse(answer.queryImages)"
                :key="url"
                style="width: 200px; height: 100px; margin-right: 10px;margin-bottom: 10px;"
                :src="url"
                :preview-src-list="JSON.parse(answer.queryImages)"
              />
            </div>
          </div>
        </div>
      </div>
      <div style="margin-left:20px;margin-top: 20px;font-weight:bold;">回答部分</div>
      <div v-if="articleForm.queryAnswers && articleForm.queryAnswers.filter(v=>v.type === 0 || v.type === 1).length > 0">
        <div style="margin-left:20px; margin-top: 15px; color:#666;">历史回答</div>
        <div v-for="answer in articleForm.queryAnswers.filter(v=>v.type === 0 || v.type === 1)" :key="answer.id">
          <div v-if="answer.type === 0">
            <div v-if="answer.attchments && answer.attchments.length > 0" style="height:70px;margin-top: 20px;display: flex;flex-direction: row; align-items: flex-start;flex-wrap: wrap;">
              <div v-for="file in answer.attchments" :key="file.id">
                <div style="margin-left: 20px;display: flex; flex-direction: column; align-items: center;">
                  <el-image
                    v-if="file.type==='图片'"
                    style="width: 100px;height: 50px;"
                    :src="baseApi + '/file/' + file.type + '/' + file.realName"
                    :preview-src-list="[baseApi + '/file/' + file.type + '/' + file.realName]"
                  />
                  <video v-if="file.type==='视频'" controls :src="baseApi + '/file/' + file.type + '/' + file.realName" style="width: 100px;height: 50px;" />
                  <audio v-if="file.type==='音乐'" controls :src="baseApi + '/file/' + file.type + '/' + file.realName" style="width: 250px;height: 50px;" />
                  <svg-icon v-if="file.type === '文档' && file.realName.indexOf('.pdf') > 0" style="width: 100px;height: 50px;" icon-class="pdf" />
                  <svg-icon v-if="file.type === '文档' && file.realName.indexOf('.pdf') < 0" style="width: 100px;height: 50px;" icon-class="attachmentdoc" />
                  <span style="max-width: 10em;margin-top:15px;word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color: #1890ff;font-size: 13px;">{{ file.name }}</span>
                </div>

              </div>
            </div>
            <div style="margin-left: 20px;margin-top: 15px; color:#1890ff;">回答: {{ answer.answerTime }}</div>
            <div style="margin-left: 20px;width: 730px; margin-top: 10px; border: 1px solid #c9d8db; padding-left: 15px;padding-right: 15px; border-radius: 4px;background: #f2f2f2;" v-html="answer.answerContent" />
          </div>
          <div v-else-if="answer.type === 1">
            <div style="margin-left: 20px;margin-top: 15px; color: red;">咨询: {{ answer.answerTime }}</div>
            <div style="margin-left: 20px;width: 730px; margin-top: 10px; border: 1px solid #c9d8db; padding-left: 15px;padding-right: 15px; border-radius: 4px;">
              <p>{{ answer.queryContent }}</p>
            </div>
            <div v-if="answer.queryImages" class="demo-image__preview">
              <el-image
                v-for="url in JSON.parse(answer.queryImages)"
                :key="url"
                style="width: 200px; height: 100px; margin-right: 10px;margin-bottom: 10px;"
                :src="url"
                :preview-src-list="JSON.parse(answer.queryImages)"
              />
            </div>
          </div>
        </div>
      </div>
      <div ref="editor" class="editor" />
      <el-button
        class="filter-item"
        size="mini"
        type="primary"
        icon="el-icon-upload"
        @click="crud.toAdd"
      >
        添加附件
      </el-button>
      <div v-if="fileLists && fileLists.length > 0" style="height:70px;margin-top: 20px;display: flex;flex-direction: row; align-items: flex-start;flex-wrap: wrap;">
        <div v-for="file in fileLists" :key="file.id">
          <div style="margin-left: 20px;display: flex; flex-direction: column; align-items: center;">
            <el-image
              v-if="file.type==='图片'"
              style="width: 100px;height: 50px;"
              :src="baseApi + '/file/' + file.type + '/' + file.realName"
              :preview-src-list="[baseApi + '/file/' + file.type + '/' + file.realName]"
            />
            <video v-if="file.type==='视频'" controls :src="baseApi + '/file/' + file.type + '/' + file.realName" style="width: 100px;height: 50px;" />
            <audio v-if="file.type==='音乐'" controls :src="baseApi + '/file/' + file.type + '/' + file.realName" style="width: 250px;height: 50px;" />
            <svg-icon v-if="file.type === '文档' && file.realName.indexOf('.pdf') > 0" style="width: 100px;height: 50px;" icon-class="pdf" />
            <svg-icon v-if="file.type === '文档' && file.realName.indexOf('.pdf') < 0" style="width: 100px;height: 50px;" icon-class="attachmentdoc" />
            <span style="max-width: 10em;margin-top:15px;word-break:keep-all;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color: #1890ff;font-size: 13px;"><a
              class="el-link--primary"
              style="color: #1890ff;"
              target="_blank"
              @click="deleteFile(file)"
            >
              <i class="el-icon-delete" style="width: 20px;height: 20px;" />
            </a>{{ file.name }}</span>

          </div>
        </div>
      </div>
      <el-button
        :loading="loading"
        style="margin-left:1.6%;margin-bottom: 30px"
        size="medium"
        type="primary"
        @click="doSubmit"
      >提交回答
      </el-button>
      <el-checkbox v-model="articleForm.sendSMS" style="margin:0 0 25px 0;">
        发送短信
      </el-checkbox>
    </el-form>
    <!--表单组件-->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.add ? '文件上传' : '编辑文件'" width="500px">
      <el-form ref="form" :model="form" size="small" label-width="80px">
        <el-form-item label="文件名">
          <el-input v-model="form.name" style="width: 370px;" />
        </el-form-item>
        <!--   上传文件   -->
        <el-form-item v-if="crud.status.add" label="上传">
          <el-upload
            ref="upload"
            :limit="1"
            :before-upload="beforeUpload"
            accept="audio/*, image/*,video/*,.doc,.pdf"
            :auto-upload="false"
            :headers="headers"
            :on-success="handleSuccess"
            :on-error="handleError"
            :on-change="handleChange"
            :action="fileUploadApi + '?name=' + form.name"
          >
            <div class="eladmin-upload"><i class="el-icon-upload" /> 添加文件</div>
            <div slot="tip" class="el-upload__tip">可上传图片,视频,音频,pdf,word文档，且不超过500M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="loading" type="primary" @click="upload">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getQuery, answerQuery } from '@/api/system/query'
import { upload } from '@/utils/upload'
import { getToken } from '@/utils/auth'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import crudFile from '@/api/tools/localStorage'
import { mapGetters } from 'vuex'
import E from 'wangeditor'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { replyQuery } from '../../../api/system/query'
const defaultForm = { id: null, name: '' }
export default {
  name: 'AnswerQuery',
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '文件', queryOnPresenterCreated: false, url: 'api/localStorage', crudMethod: { ...crudFile }})
  },
  data() {
    return {
      loading: false,
      articleForm: { queryTitle: '', queryContent: '', dept: {}, price: 0, attachmentIds: [] },
      rules: {
        queryAnswer: [
          { required: true, message: '回答内容不能为空', trigger: 'blur' }
        ]
      },
      headers: { 'Authorization': getToken() },
      fileLists: []
    }
  },
  // 设置数据字典
  dicts: ['article_status', 'article_type'],
  computed: {
    ...mapGetters([
      'imagesUploadApi',
      'baseApi',
      'fileUploadApi',
      'user'
    ])
  },
  mounted() {
    const _this = this
    this.crud.optShow.add = false

    var e2 = new E(this.$refs.summary)
    // 自定义菜单配置
    e2.config.zIndex = 10
    e2.config.showFullScreen = false
    // 配置菜单栏，删减菜单，调整顺序
    e2.config.menus = [
      'bold',
      'italic',
      'underline',
      'indent',
      'lineHeight',
      'foreColor'
    ]

    e2.config.onchange = (html) => {
      this.articleForm.freeReply = html
    }
    // 设置编辑区域高度为 500px
    e2.config.height = 200
    e2.create()

    var editor = new E(this.$refs.editor)
    // 自定义菜单配置
    editor.config.zIndex = 10
    // 文件上传
    editor.config.customUploadImg = function(files, insert) {
      // files 是 input 中选中的文件列表
      // insert 是获取图片 url 后，插入到编辑器的方法
      files.forEach(image => {
        upload(_this.imagesUploadApi, image).then(res => {
          const data = res.data
          const url = _this.baseApi + '/file/' + data.type + '/' + data.realName
          insert(url)
        })
      })
    }
    editor.config.excludeMenus = ['video', 'code']
    editor.config.onchange = (html) => {
      this.articleForm.queryAnswer = html
    }
    editor.config.height = 600
    editor.create()
    getQuery(this.$route.query.id).then(res => {
      this.articleForm = res
      this.articleForm.queryAnswers = this.articleForm.queryAnswers.sort((a, b) => a.id - b.id)
      this.articleForm.answerUserId = res.answerUser ? res.answerUser.id : null
      this.fileLists = res.attachments || []
      editor.txt.html(this.articleForm.queryAnswer)
    })
  },

  methods: {
    handleChange(file, fileList) {
      this.form.name = file.name
    },
    deleteFile(file) {
      this.$confirm(`确认删除${file.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('删除file', file)
        this.crud.doDelete([file])
        this.fileLists.splice(this.fileLists.indexOf(file), 1)
      }).catch(() => {
      })
    },
    upload() {
      this.$refs.upload.submit()
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 500
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 200MB!')
      }
      return isLt2M
    },
    handleSuccess(response, file, fileList) {
      console.log(response)
      this.fileLists.push(response)
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.$refs.upload.clearFiles()
      this.crud.status.add = CRUD.STATUS.NORMAL
      this.crud.resetForm()
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    doReply() {
      if (this.articleForm.freeReply && this.articleForm.freeReply.length > 0) {
        this.loading = true
        if (!this.articleForm.answerUserId) {
          this.articleForm.answerUserId = this.user.id
        }
        this.articleForm.queryId = this.articleForm.id
        this.articleForm.answerTime = new Date().getTime()
        replyQuery(this.articleForm).then(res => {
          this.$notify({
            title: '回复成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.back()
        }).catch(err => {
          this.loading = false
          console.log(err.response.data.message)
        })
      }
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.loading = true
          if (this.fileLists) {
            this.articleForm.attachmentIds = this.fileLists.map(v => `${v.id}`).join(';')
          }
          if (!this.articleForm.answerUserId) {
            this.articleForm.answerUserId = this.user.id
          }
          this.articleForm.queryId = this.articleForm.id
          this.articleForm.answerTime = new Date().getTime()
          answerQuery(this.articleForm).then(res => {
            this.$notify({
              title: '回答成功',
              type: 'success',
              duration: 2500
            })
            this.loading = false
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.back()
          }).catch(err => {
            this.loading = false
            console.log(err.response.data.message)
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.editor {
  text-align: left;
  margin: 20px;
  width: 730px;
}
.filter-item {
  margin-left: 20px;
}
/* ::v-deep .w-e-text-container {
  height: 360px !important;
} */
.summary {
  text-align: left;
  width: 640px;
  height: 100px;
  display:inline-block;
}
</style>
